<template>
  <div class="collections-page">
    <!-- 左侧收藏夹列表 -->
    <el-card class="folder-list-card">
      <div class="folder-list-header">
        <span>收藏夹</span>
        <el-button type="primary"
                   size="small"
                   @click="showAddFolder = true"
        >新增收藏夹</el-button
        >
      </div>
      <el-menu
        :default-active="activeFolderId"
        class="folder-list"
        @select="handleFolderSelect"
      >
        <el-menu-item
          v-for="folder in folders"
          :key="folder.id"
          :index="folder.id.toString()"
        >
          <div class="folder-name">{{ folder.name }}</div>
          <div>
            <el-icon class="folder-action" @click.stop="editFolder(folder)">
              <edit />
            </el-icon>
            <el-icon class="folder-action" @click.stop="confirmDeleteFolder(folder)">
              <delete />
            </el-icon>
          </div>
        </el-menu-item>
      </el-menu>
    </el-card>

    <!-- 右侧文章列表 -->
    <el-card class="article-list-card">
      <div class="article-list-header">
        <span>收藏文章</span>
      </div>
      <el-table
        :data="articleList"
        border
        style="width: 100%; margin-top: 16px"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column prop="article.title" label="标题" />
        <el-table-column prop="article.published_at" label="日期" />
        <el-table-column prop="article.user.name" label="作者" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="danger" size="small" @click="cancelCollect(scope.row)">
              取消收藏
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination" style="text-align: right; margin-top: 16px">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="page"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/修改收藏夹弹窗 -->
    <el-dialog
      v-model="showAddFolder"
      :title="editFolderData ? '修改收藏夹' : '新增收藏夹'"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      @close="resetFolderDialog"
    >
      <el-form :model="folderForm">
        <el-form-item label="收藏夹名称" required>
          <el-input v-model="folderForm.name" maxlength="20" />
        </el-form-item>
        <el-form-item label="是否公开" required>
          <el-radio-group v-model="folderForm.is_public" style="margin-left: 20px">
            <el-radio :label="1">公开</el-radio>
            <el-radio :label="0">私有</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddFolder = false">取消</el-button>
        <el-button type="primary" @click="saveFolder">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除收藏夹确认弹窗 -->
    <el-dialog v-model="showDeleteConfirm"
               title="删除确认"
               width="350px"
               center>
      <div>
        确定要删除收藏夹 <b>{{ deleteFolderData?.name }}</b> 吗？此操作不可恢复。
      </div>
      <template #footer>
        <el-button @click="showDeleteConfirm = false">取消</el-button>
        <el-button type="danger" @click="deleteFolder">确认删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import * as collectApi from '@/api/collection';

// 收藏夹数据
interface Folder {
  id: number;
  name: string;
  is_public: number;
}
const folders = ref<Folder[]>([]);
const activeFolderId = ref('1');

// 收藏文章数据
interface Article {
  id: number;
  title: string;
  date: string;
  author: string;
  article_id: number;
  folder_id: number;
}

const articleList = ref<Article[]>([]);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 收藏夹弹窗相关
const showAddFolder = ref(false);
const folderForm = reactive({ name: '', is_public: 1, id: null as number | null });
const editFolderData = ref<Folder | null>(null);

// 删除弹窗相关
const showDeleteConfirm = ref(false);
const deleteFolderData = ref<Folder | null>(null);

// 初始化文章列表
const loadArticles = async() => {
  const obj = {
    id: activeFolderId.value,
    page: page.value,
    size: pageSize.value
  };
  try {
    const res = await collectApi.getFoldersArtList(obj);
    console.log('res', res);
    articleList.value = res.data.articles || [];
    total.value = res.data.pagination.total || 0;
  } catch (error) {
    console.error(error);
  }
};

// 选择收藏夹且获取文章列表
function handleFolderSelect(id: string) {
  activeFolderId.value = id;
  page.value = 1;
  loadArticles();
}

// 新增/修改收藏夹
const saveFolder = async() => {
  if (!folderForm.name.trim()) {
    ElMessage.warning('收藏夹名称不能为空');
    return;
  }
  try {
    if (editFolderData.value) {
      // 修改
      const res = await collectApi.editFolders(folderForm);
      console.log('res', res);
      getFolders();
      ElMessage.success('收藏夹修改成功');
    } else {
      // 新增
      await collectApi.addFolders(folderForm);
      getFolders();
      ElMessage.success('收藏夹新增成功');
    }
  } catch (error) {
    console.error(error);
  }
  showAddFolder.value = false;
  resetFolderDialog();
};
// 编辑收藏夹
function editFolder(folder: Folder) {
  editFolderData.value = folder;
  folderForm.name = folder.name;
  folderForm.id = folder.id;
  showAddFolder.value = true;
}
// 重置收藏夹弹窗数据
function resetFolderDialog() {
  folderForm.name = '';
  editFolderData.value = null;
}

// 删除收藏夹
function confirmDeleteFolder(folder: Folder) {
  deleteFolderData.value = folder;
  showDeleteConfirm.value = true;
}
const deleteFolder = async() => {
  if (deleteFolderData.value) {
    await collectApi.delFolders(deleteFolderData.value.id);
    getFolders();
    ElMessage.success('收藏夹已删除');
  }
  showDeleteConfirm.value = false;
  deleteFolderData.value = null;
};

// 文章分页
function handlePageChange(val: number) {
  page.value = val;
  loadArticles();
}

// 取消收藏
const cancelCollect = async(row: Article) => {
  try {
    await collectApi.favorite({ id: row.article_id, folder_id: row.folder_id });
    ElMessage.success('已取消收藏');
    loadArticles();
  } catch (error) {
    console.error(error);
  }
};
// 获取收藏夹列表
const getFolders = async() => {
  const res = await collectApi.getFoldersList({ page: 1, size: 50 });
  activeFolderId.value = res.data?.[0]?.id?.toString() || '';
  if (activeFolderId.value) {
    loadArticles();
  }

  folders.value = res.data;
};
getFolders();
</script>

<style scoped>
.collections-page {
  display: flex;
  gap: 24px;
  padding: 24px;
  background: #f5f7fa;
  min-height: 600px;
}
.folder-list-card {
  width: 260px;
  min-width: 220px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px #eee;
  padding: 0 0 12px 0;
}
.folder-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  font-weight: bold;
  font-size: 16px;
}
.folder-list {
  border: none;
  background: transparent;
}
.folder-name {
  width: 80%;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  text-align: left;
}
.folder-list .el-menu-item {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  padding: 0 6px;
}
.folder-list .el-menu-item.is-active {
  background: #e1f3d8;
  color: #67c23a;
}
.el-menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 15px;
  border-radius: 6px;
  margin: 2px 8px;
  background: #f8f8f8;
  transition: background 0.2s;
}
.el-menu-item.is-active {
  background: #e1f3d8;
  color: #67c23a;
}
.folder-action {
  margin-left: 8px;
  color: #909399;
  cursor: pointer;
  transition: color 0.2s;
}
.folder-action:hover {
  color: #409eff;
}
.article-list-card {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px #eee;
  padding: 16px;
  min-width: 400px;
}
.article-list-header {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
}
.pagination {
  margin-top: 16px;
}
</style>
